<template>
    <div id="login">
        <div class="login">
            <img src="@/assets/img/web/login-user.jpg" class="login-user" />
            <img src="@/assets/img/web/login-user-bg.jpg" class="login-user-bg" />
            <div class="content">
                <a-spin size="large" :spinning="isLoading">
                    <div class="title">登录</div>
                    <div class="form">
                        <a-form :model="formState" name="basic" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }"
                            autocomplete="off" @finish="onFinish">
                            <a-form-item label="账号" name="username" :rules="[{ required: true, message: '请输入账号' }]">
                                <a-input v-model:value="formState.username" />
                            </a-form-item>

                            <a-form-item label="密码" name="password" :rules="[{ required: true, message: '请输入密码' }]">
                                <a-input-password v-model:value="formState.password" />
                            </a-form-item>

                            <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
                                <a-button type="primary" html-type="submit">登录</a-button>
                            </a-form-item>
                        </a-form>
                    </div>
                </a-spin>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { message } from 'ant-design-vue';
import { login } from "@/api/admin";   //引入api
import { useRoute, useRouter } from 'vue-router';
import { generateRouter, setAdminAddRoute } from '@/router/adminLoginRouter.js';

//删除所有缓存数据
localStorage.clear();

const route = useRoute();
const router = useRouter();

const isLoading = ref(false);    // 控制loading

const local_server_route = ref([]);
const redirectUrl = ref('');

const server_route = ref([]);

const formState = reactive({
    username: '',
    password: '',
    remember: true,
});

// 菜单列表，需要处理成项目需要的格式
const menuToRoute = async () => {
    local_server_route.value.map((_route) => {
        var one_server_route = { path: '', component: '', meta: {}, children: [] };
        one_server_route.path = '';
        one_server_route.component = '';
        one_server_route.meta = { menuName: _route.name, order: _route.sort };
        // one_server_route.children = [];

        const children = _route.sub;
        if (Array.isArray(children) && children?.length > 0) {
            children.map((childRoute) => {

                var one_child_route = { path: '', component: '', name: '', meta: {} };
                one_child_route.path = '/admin/' + childRoute.url;
                one_child_route.component = '/admin/' + childRoute.url;

                one_child_route.name = _route.key + '-' + childRoute.key;
                // var childRoutePath = childRoute.url.split('/')
                // 用vite提供的动态导入功能，根据字符串从views目录下导入组件
                // 参考：https://cn.vitejs.dev/guide/features.html#dynamic-import
                // if (childRoutePath.length === 1) {
                //     // 如果是单个vue文件
                //     one_child_route.component = () => import(`@/views/admin/${childRoutePath[0]}.vue`)
                // } else {
                //     // 否则就是一个目录
                //     one_child_route.component = () => import(`@/views/admin/${childRoutePath[0]}/${childRoutePath[1]}.vue`)
                // }
                one_child_route.meta = { menuName: childRoute.name, order: childRoute.sort };
                one_server_route.children.push(one_child_route);
            })
        }
        server_route.value.push(one_server_route);
    });


    let routerList = server_route.value;

    localStorage.setItem("vue3-vite5-admin-routerList", JSON.stringify(routerList));    //菜单列表，需要处理成项目需要的格式
    // 生成路由树
    let list = generateRouter(routerList);
    // 添加路由
    setAdminAddRoute(list);

    router.replace(redirectUrl.value);
}

const onFinish = values => {
    isLoading.value = true

    login(formState).then((res) => {
        isLoading.value = false
        if (res === false) return;

        local_server_route.value = res.data.menu;

        // 处理有权限的操作按钮列表
        var adminOption = ref('--');
        var adminOptionApi = res.data.option;
        for (let _main in adminOptionApi) {
            for (let _sub in adminOptionApi[_main]) {
                for (let _option in adminOptionApi[_main][_sub]) {
                    if (adminOptionApi[_main][_sub][_option] === 1) {
                        adminOption.value += _main + ',' + _sub + ',' + _option + '--';
                    }
                }
            }
        }

        localStorage.setItem("vue3-vite5-admin-token", res.data.token);    //菜单列表，需要处理成项目需要的格式
        localStorage.setItem("vue3-vite5-admin-menu", JSON.stringify(res.data.menu));    //菜单列表，需要处理成项目需要的格式
        localStorage.setItem("vue3-vite5-admin-option", adminOption.value); //有权限的操作按钮列表
        localStorage.setItem("vue3-vite5-admin-user-name", res.data.user.name); //登录用户名
        localStorage.setItem("vue3-vite5-admin-user-position", res.data.user.position); //登录职位

        redirectUrl.value = res.data.redirect;

        menuToRoute();

        message.success('登录成功');
    }).catch((rej) => {
        isLoading.value = false
        message.error('错误：' + rej)
    });
};
</script>

<style scoped>
.login {
    width: 100%;
    height: 100%;
}

.bg {
    display: block;
}

.login-user {
    position: fixed;
    height: 100%;
    top: 0;
    left: 0;
    z-index: -1;
}

.login-user-bg {
    position: fixed;
    height: 100%;
    width: 100%;
    top: 0;
    right: 0;
    z-index: -2;
}

.content {
    position: absolute;
    top: 20%;
    right: 20%;
    /* transform: translate(-50%, -50%); */
    width: 400px;
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
    z-index: 2;
    padding: 20px;
}

.title {
    text-align: center;
    font-size: 30px;
    margin-top: 50px;
    font-weight: bold;
}

.form {
    margin-top: 50px;
}

:deep(.form) {
    padding-right: 10%;
}

:deep(.ant-btn) {
    width: 50%;
}
</style>
